<template>
  <el-dialog :title="title" :visible="visible" width="60%" :show-close="true" @close="close" :close-on-click-modal="false">
    <el-form :model="ruleForm" :rules="rules" ref="formRef" label-width="120px" class="demo-ruleForm">
      <el-form-item label="物料类型" prop="materialType">
        <el-select v-model="ruleForm.materialType" placeholder="请选择物料类型" class="w-100">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料单价" prop="price">
        <el-input type="number" v-model="ruleForm.price" placeholder="请输入物料单价" class="w-100">
          <template slot="append">元/克</template>
        </el-input>
      </el-form-item>
      <el-form-item label="物料重量" prop="weight"
      ">
      <el-input type=" number" v-model="ruleForm.weight" placeholder="请输入物料重量" class="w-100">
        <template slot="append">克</template>
      </el-input>
      </el-form-item>
      <el-form-item label="物料总价" prop="totalAmount">
        <el-input type="number" v-model="ruleForm.totalAmount" placeholder="自动计算" class="w-100" readonly>
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="交易时间" prop="tradeTime">
        <el-date-picker v-model="ruleForm.tradeTime" type="datetime" placeholder="请选择交易时间" class="w-100"
                        format="yyyy-MM-dd HH:mm:ss"/>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input type="textarea" v-model="ruleForm.remarks" placeholder="请输入备注" class="w-100"/>
      </el-form-item>
      <el-form-item label="附件" prop="accessoryGroupId">
        <div class="multi-upload-container">
          <!-- 上传组件 -->
          <el-upload action="#" list-type="picture-card" :multiple="true" :file-list="fileList"
                     :before-upload="beforeUpload" :on-change="handleChange" :on-remove="handleRemove"
                     :auto-upload="false" :limit="9" :on-exceed="handleExceed" accept="image/*">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              请上传图片文件，单张图片不超过5MB
            </div>
          </el-upload>

          <!-- 上传按钮 -->
          <el-button type="primary" @click="submitUpload" :loading="uploading"
                     :disabled="fileList.length === 0">
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>

          <!-- 结果展示 -->
          <div v-if="uploadedUrls.length > 0" class="result-container">
            <h4>上传成功：</h4>
            <div v-for="(url, index) in uploadedUrls" :key="index" class="image-item">
              <el-image :src="url" fit="cover"
                        style="width: 100px; height: 100px; margin-right: 10px;"></el-image>
              <div class="image-url">{{ url }}</div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
        </span>
  </el-dialog>
</template>

<script>
import {stockCustomerItem, subCustomerItem} from '../api/customer';
import {IMG_URL} from '@/utils/utils';
import {createDirectClient} from '@/utils/oss'
import {uploadAccessory} from '@/api/login'
import moment from "moment/moment";

export default {
  name: 'AddOrEdit',
  components: {},
  data() {
    return {
      fileList: [], // 待上传文件列表
      uploadedUrls: [], // 已上传成功的URL
      uploading: false,
      IMG_URL,
      options: [
        {
          label: '黄金',
          value: 'GOLD'
        },
        {
          label: '白银',
          value: 'SILVER'
        },
        {
          label: '铂金',
          value: 'PLATINUM'
        },
        {
          label: '钯金',
          value: 'PALLADIUM'
        }
      ],
      title: '',
      visible: false,
      loading: false,
      ruleForm: {
        cusId: null,
        materialType: null,
        price: null,
        weight: null,
        totalAmount: null,
        tradeTime: null,
        remarks: null,
        accessoryGroupId: null,
      },
      rules: {
        materialType: [
          {required: true, message: '请选择物料类型', trigger: 'change'},
        ],
        price: [
          {required: true, message: '请输入物料单价', trigger: 'blur'}
        ],
        weight: [
          {required: true, message: '请输入物料重量', trigger: 'blur'}
        ],
        tradeTime: [
          {type: 'date', required: true, message: '请选择交易时间', trigger: 'change'}
        ],
      },
      operationType: 'add'
    }
  },
  computed: {
    // 自动计算物料总价
    calculatedTotalAmount() {
      if (this.ruleForm.price && this.ruleForm.weight) {
        return (parseFloat(this.ruleForm.price) * parseFloat(this.ruleForm.weight)).toFixed(2);
      }
      return '';
    },
  },
  watch: {
    // 监听单价和重量变化，自动更新总价
    'ruleForm.price': function (newVal) {
      if (newVal && this.ruleForm.weight) {
        this.ruleForm.totalAmount = this.calculatedTotalAmount;
      }
    },
    'ruleForm.weight': function (newVal) {
      if (newVal && this.ruleForm.price) {
        this.ruleForm.totalAmount = this.calculatedTotalAmount;
      }
    }
  },
  created() {
  },
  methods: {
    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.fileList = fileList
    },

    // 移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
    },

    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${fileList.length} 张图片`)
    },

    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt5M) {
        this.$message.error('单张图片大小不能超过5MB!')
      }

      return isImage && isLt5M
    },

    // 提交上传
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择图片')
        return
      }
      this.uploading = true
      this.uploadedUrls = []

      try {
        const client = createDirectClient()
        console.log(this.fileList, '提交上传fileList');

        const uploadPromises = this.fileList.map(file => {
          let fileSuffix = `.${file.name.split('.')[1]}`;
          let prefix = process.env.VUE_APP_CERT_SAVE_PREFIX + moment(new Date()).format("yyyyMMDD") + "/" + moment(new Date()).format("yyyyMMDDHHmmssSSS") + fileSuffix;
          client.multipartUpload(prefix, file.raw).then(res => {
            let params = {
              dataClassify: 'other',
              groupId: this.ruleForm.accessoryGroupId || '',
              filePath: res.name,
              storageMethod: 'oss'
            }
            uploadAccessory(params).then(res => {
              this.$message.success('附件上传成功!')
              this.ruleForm.accessoryGroupId = res
            }).catch(error => {
              console.error('附件上传失败:', error)
            })
          }).catch(error => {
            console.error('OSS上传失败:', error)
          })
        })
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('上传失败，请重试')
      } finally {
        this.uploading = false
      }
    },
    operation(row, type) {
      this.visible = true;
      this.title = type === 'add' ? '入料' : '回料';
      let temp = {};
      Object.keys(this.ruleForm).forEach(key => {
        temp[key] = null;
      })
      temp.cusId = row;
      this.ruleForm = temp;
      this.operationType = type;
    },
    close() {
      this.$refs.formRef.resetFields();
      this.ruleForm.accessoryGroupId = null;
      this.visible = false;
      this.fileList = [] // 清空待上传列表
      this.uploadedUrls = [] // 清空已上传成功的URL
    },
    submit() {
      this.$refs.formRef.validate(async (res) => {
        if (res) {
          this.loading = true;
          try {
            const p = {...this.ruleForm}

            let res = await this.operationType === 'add' ? stockCustomerItem(p) : subCustomerItem(p);
            this.loading = false;
            this.$refs.formRef.resetFields();
            const msg = this.title + '成功';
            this.$message({
              type: 'success',
              message: msg
            })
            this.close();
            this.$emit('refresh', 1);
          } catch (err) {
            console.log(err);

            this.loading = false;
          }
        }
      })
    }
  },
}
</script>

<style lang='scss' scoped>
.multi-upload-container {
  padding: 20px;
}

.result-container {
  margin-top: 20px;
}

.image-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.image-url {
  margin-left: 10px;
  word-break: break-all;
  font-size: 12px;
  color: #666;
}
</style>